﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SCRendererYUV422P : SCCanvas {

    private Material mat;
    private byte[] cacheY, cacheU, cacheV;
    public SCRendererYUV422P(OutPixFmt fmt)
    {
        texs = new Texture2D[3];
    }

    public override void InitCanvas(ref Material mat, VideoStream vs)
    {
        base.InitCanvas(ref mat, vs);
        this.mat = mat = new Material(Resources.Load<Material>("StreamCapture/SCMatXYUVX"));
        texs[0] = new Texture2D(width, height, TextureFormat.R8, false);
        texs[1] = new Texture2D(width / 2, height, TextureFormat.R8, false);
        texs[2] = new Texture2D(width / 2, height, TextureFormat.R8, false);
    }

    public override void Renderer(Frame frame)
    {

        if (frame == null) return;

        if (frame.format != (int)OutPixFmt.PIX_FMT_YUV422P && frame.format != (int)OutPixFmt.PIX_FMT_YUVJ422P)
        {
            Debug.LogError("The pixel format is different from the canvas type");
            return;
        }

        if (frame.linesize[0] != width || frame.linesize[1] != width / 2 || frame.linesize[2] != width / 2)
        {
            if (cacheY == null)
            {
                cacheY = new byte[width * height];
                cacheU = new byte[width * height / 2];
                cacheV = new byte[width * height / 2];
            }
            frame.data[0] = IStreamCapture.MemoryAlignment(frame.data[0], width, height, frame.linesize[0], cacheY);

            frame.data[1] = IStreamCapture.MemoryAlignment(frame.data[1], width / 2, height / 2, frame.linesize[1], cacheU);

            frame.data[2] = IStreamCapture.MemoryAlignment(frame.data[2], width / 2, height / 2, frame.linesize[2], cacheV);
        }

        texs[0].LoadRawTextureData(frame.data[0], width * height);
        texs[1].LoadRawTextureData(frame.data[1], width * height / 2);
        texs[2].LoadRawTextureData(frame.data[2], width * height / 2);


        texs[0].Apply();
        texs[1].Apply();
        texs[2].Apply();


        mat.SetTexture("_YTex", texs[0]);
        mat.SetTexture("_UTex", texs[1]);
        mat.SetTexture("_VTex", texs[2]);
    }
}
